package com.yz.controller;



import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yz.common.annotation.Login;
import com.yz.common.annotation.LoginUser;
import com.yz.common.entity.DepartmentEntity;
import com.yz.common.entity.UrlForm;
import com.yz.common.entity.UserEntity;
import com.yz.common.utils.R;
import com.yz.form.ChangeNameForm;
import com.yz.form.RegisterForm;
import com.yz.service.DepartmentService;
import com.yz.service.TokenService;
import com.yz.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户相关操作放到
 * @author yz对的ghj

 *
 */
@RestController
@RequestMapping("/api")
@Api(tags="用户")
public class ApiUserController {
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @Login
    @GetMapping("getDepartment")
    @ApiOperation(value="获取部门信息", response=DepartmentEntity.class)
    public R getDepartment(@RequestHeader("token")String token,@RequestParam("id")long id,@ApiIgnore @LoginUser UserEntity user){
        DepartmentEntity data = departmentService.selectOne(new EntityWrapper<DepartmentEntity>().eq("dept_id",id));
        return R.ok().put("data", data);
    }

    @Login
    @GetMapping("userInfo")
    @ApiOperation(value="获取用户信息", response=UserEntity.class)
    public R userInfo(@RequestHeader("token")String token,@ApiIgnore @LoginUser UserEntity user){
        return R.ok().put("data", user);
    }

    @PostMapping("changeHead")
    @ApiOperation("修改头像")
    @ResponseBody
    @Login
    public R changeHead(@RequestHeader("token")String token,@RequestBody UrlForm url,
                        @ApiIgnore @LoginUser UserEntity user) throws IOException {
        user.setHeadUrl(url.getUrl());
        userService.updateById(user);
        return R.ok().put("data",null);
    }


    @PostMapping("register")
    @ApiOperation("注册")
    @ResponseBody
    public R register(@RequestBody RegisterForm form,
                        @ApiIgnore @LoginUser UserEntity user) throws IOException {
        try {
            userService.register(form);
            return R.ok().put("data",null);
        }catch (Exception e){
            return R.error().put("data",null).put("msg","用户已注册");
        }
    }
}
